package com.cskaoyan.utils;

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

/**
 * 创建日期: 2022/04/21 11:08
 *
 * @author ciggar
 */
public class JDBCUtils {

    static String url;
    static String username;
    static String password;
    static String driver;


    static {

        try {
            Properties properties = new Properties();
            FileInputStream fileInputStream = new FileInputStream("jdbc.properties");
            properties.load(fileInputStream);

            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            driver = properties.getProperty("driver");

        }catch (Exception ex) {
            System.out.println("读取配置文件异常！！！");
        }
    }



    // 获取Connection对象
    public static Connection getConnection(){

        Connection connection = null;

        try {

            // 解耦
            Class.forName(driver);



            // 1. 建立网络连接  Connection对象表示网络连接
            connection = DriverManager.getConnection(url, username, password);

        }catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("获取Connection对象异常！！");
        }

        return connection;

    }


    // 断开连接
    public static void close(Connection connection, Statement statement, ResultSet resultSet){

        try {
            try {
                if (resultSet != null) resultSet.close();
            } finally {
                try {
                    if (statement != null) statement.close();
                }finally {
                    if (connection != null) connection.close();
                }
            }


            // 指令重排
            // 如果保证指令不重排呢？
            // volatile 修饰在变量之前  |
            // -- 1. 内存可见性   2. 禁止指令重排

            //            int i = 0;
            //
            //            int j = 1;
            //
            //            int m = i+j;




        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

}
